#pragma once

#include <iostream>
#include <cstdio>
#include <cassert>
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "Log.hpp"

using namespace std;  // 将std直接展开简答,但不推荐

#define PATH_NAME "/home/Joy"
#define PROJ_ID 0x66
#define SHM_SIZE 4096 //共享内存的大小,最好是页(PAGE:4096KB)的整数倍
#define FIFO_NAME "./fifo"

// 将十进制转为十六进制
string TransToHex(key_t k)
{
    char buffer[32];
    snprintf(buffer, sizeof buffer, "0x%x", k);
    return buffer;
}

class Init
{
public:
    Init()
    {
        umask(0);
        int n = mkfifo(FIFO_NAME, 0666);
        assert(n == 0);
        (void)n;
        Log("create fifo success", Notice) << endl;
    }

    ~Init()
    {
        unlink(FIFO_NAME);
        Log("delete fifo success", Notice) << endl;
    }
};

#define READ O_RDONLY
#define WRITE O_WRONLY

int OpenFIFO(std::string pathname, int flags)
{
    int fd = open(pathname.c_str(), flags);
    assert(fd != -1);
    return fd;
}

// 服务端等待客户端唤醒
void Wait(int fd)
{
    Log("等待中......", Notice) << endl;
    uint32_t temp = 0;
    ssize_t s = read(fd, &temp, sizeof(uint32_t));
    assert(s == sizeof(uint32_t));
    (void)s;

}

// 客户端唤醒服务端
void Signal(int fd)
{
    uint32_t temp = 1;
    ssize_t s = write(fd, &temp, sizeof(uint32_t));
    assert(s == sizeof(uint32_t));
    (void)s;
    Log("唤醒中......", Notice) << endl;
}

void CloseFIFO(int fd)
{
    close(fd);
}